package mk.timska_rabota_android.messages;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import mk.timska_rabota_android.SendMessage;
import mk.timska_rabota_android.contacts.Contact;
import mk.timska_rabota_android.contacts.ContactsModule;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;

public class MessagesModule {
	public static String regId = "mk.timska_rabota_android.regId";
	public static String appVer = "mk.timska_rabota_android.appVersion";
	public static String appId = "295943527546";
	public static GoogleCloudMessaging gcm = null;
	
	
	@SuppressWarnings("unchecked")
	public static void registerInBackground(final Context con, final Activity act){
		
		
		
		new AsyncTask(){
			String registrationCode;
			@Override
			protected String doInBackground(Object... Params) {
				String msg = "";
				registrationCode=null;
				try {
	                if (gcm == null) {
	                    gcm = GoogleCloudMessaging.getInstance(con);
	                }
	                registrationCode = gcm.register(appId);
	                msg = "Device registered, registration ID=" + registrationCode;

	                //sendRegistrationIdToBackend();
	                
	                saveRegistrationId(con, act, registrationCode);
	                
	            } catch (IOException ex) {
	                msg = "Error :" + ex.getMessage();
	            }
	            return msg;
			}

			protected void onPostExecute(){
				Toast t = Toast.makeText(con, registrationCode, Toast.LENGTH_LONG);
			}
			
		}.execute(null,null,null);
		
		
		
	}
	
	public static String getRegistrationId(Context context, Activity act){
		final SharedPreferences pref = getSharedPreferences(context, act);
		String registrationId = pref.getString(regId, "");
		if(registrationId.compareTo("")==0){
			registerInBackground(context ,act);
			return "";
		}
		return registrationId;
	}
	
	public static SharedPreferences getSharedPreferences(Context con, Activity act){
		return act.getSharedPreferences(SendMessage.class.getSimpleName(), Context.MODE_PRIVATE);
	}
	
	public static void saveRegistrationId(Context con, Activity act, String registrationId){
		final SharedPreferences pref = getSharedPreferences(con, act);
		int appVersion = getAppVersion(con);
		SharedPreferences.Editor editor = pref.edit();
		editor.putString(regId, registrationId);
		editor.putInt(appVer, appVersion);
		editor.commit();
	}
	
	private static int getAppVersion(Context context) {
	    try {
	        PackageInfo packageInfo = context.getPackageManager()
	                .getPackageInfo(context.getPackageName(), 0);
	        return packageInfo.versionCode;
	    } catch (NameNotFoundException e) {
	        throw new RuntimeException("Could not get package name: " + e);
	    }
	}
	
	public static void sendRegistrationId(Context con, Activity act, String registrationId, String URL){
		HttpClient httpClient = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(URL);
		List<NameValuePair> data = new ArrayList<NameValuePair>(2);
		final SharedPreferences prefs = getSharedPreferences(con, act);
		String mail = "";
		prefs.getString(ContactsModule.email, mail);
		
		data.add(new BasicNameValuePair("email", mail)); //Treba da se vnesi mailot na momentalniot korisnik
		data.add(new BasicNameValuePair("reg_id", registrationId));
		
		try{
			httpPost.setEntity(new UrlEncodedFormEntity(data));
		} 
		catch(UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		// Making HTTP Request
		try {
		    HttpResponse response = httpClient.execute(httpPost);
		 
		    // writing response to log
		    Log.d("Http Response:", response.toString());
		 
		} catch (ClientProtocolException e) {
		    // writing exception to log
		    e.printStackTrace();
		         
		} catch (IOException e) {
		    // writing exception to log
		    e.printStackTrace();
		}
	}
	
	public static void receiveMessage(Message msg){
		//we get the message here, should split by recipients and save it in a database or file
		
		
	}

	public static ArrayList<Message> getMyMessages(Contact sender){
		ArrayList<Message> retVal = new ArrayList<Message>();
		/* To-Do
		 * Da se izraboti vrakanje na poraki, najverojatno ke se grupiraat po prakaci
		 * */
		retVal.add(new Message(1,"Test porakiii","Primac", 1.,2.,3.));
		retVal.add(new Message(2,"Test porakiii","Primac", 1.,2.,3.));
		retVal.add(new Message(3,"Test porakiii","Primac", 1.,2.,3.));
		retVal.add(new Message(4,"Test porakiii","Primac", 1.,2.,3.));
		retVal.add(new Message(5,"Test porakiii","Primac", 1.,2.,3.));
		retVal.add(new Message(6,"Test porakiii","Primac", 1.,2.,3.));
		retVal.add(new Message(7,"Test porakiii","Primac", 1.,2.,3.));
		retVal.add(new Message(8,"Test porakiii","Primac", 1.,2.,3.));
		retVal.add(new Message(9,"Test porakiii","Primac", 1.,2.,3.));
		retVal.add(new Message(10,"Test porakiii","Primac", 1.,2.,3.));
		
		
		
		return retVal;
	}
	
	public static ArrayList<String> messagesToString(ArrayList<Message> a){
		ArrayList<String> retVal = new ArrayList<String>();
		Iterator<Message> iter = a.iterator();
		while(iter.hasNext()){
			retVal.add(iter.next().toString());
		}
		return retVal;
	}


}
